const cheerio = require('cheerio')
const log4js = require('log4js')
const request = require('request-promise')
const schedule = require('node-schedule')
const config = require('../config')
const moment = require('moment')
const Redis = require('ioredis')
const redis = new Redis(config.redis)

// 配置log4js
log4js.configure(config.log4js)
const logger = log4js.getLogger('币安')

const prefix = 'https://support.binance.com'
const url = '/hc/zh-cn/sections/115000106672-%E6%96%B0%E5%B8%81%E4%B8%8A%E7%BA%BF'

let latestNews = null

async function getNews () {
  try {
    let html = await request(prefix + url)
    let $ = cheerio.load(html)
    let article = $('.article-list .article-list-item:nth-child(1) .article-list-link')[0]
    if (article) {
      let title = $(article).text().trim()
      if (latestNews && latestNews.title === title) {
        return null
      } else {
        latestNews = {
          type: 4,
          title: title,
          content: '',
          source: '币安',
          time: moment().utcOffset(8).format('YYYY-MM-DD HH:mm:ss')
        }
        return latestNews
      }
    } else {
      logger.error('获取公告失败')
      return null
    }
  } catch (e) {
    logger.error(e.message)
    return null
  }
}

/**
 * 每4秒执行一次查询
 */
schedule.scheduleJob('*/4 * * * * *', async () => {
  let news = await getNews()
  news && console.log(news)
  news && redis.publish('news', JSON.stringify(news))
})
